Understanding objects and naming in Python can be difficult. In this demo we'll follow a post Is Python call-by-value or call-by-reference? Neither..
First, let's make some objects. Everything in Python is an object.
#So when we make a string it's an object. When we call it a variable name, it binds that name to the string object.
fruit = 'apple'
#When we make a list, it will point to the object bound by fruit
lunch = []
lunch.append(fruit)
dinner = lunch
dinner.append('fish')
fruit = 'pear'
meals = [fruit, lunch, dinner]
print(meals)
Let's check the object ids for both lists
print(id(lunch))
print(id(dinner))
Notice what happens when we append to list that is bound to both lunch
and dinner
:
dinner.append('pasta')
print(lunch, dinner)
lunch.append('carrots')
print(lunch,dinner)
We've looked at mutable and immutable. Tuples are an example of immutable objects.
fruits = ['apple', 'banana', 'orange']
veggies = ['carrot', 'broccoli']
food_tuple = (fruits, veggies)
print(food_tuple)
fruits.append('plum')
print(fruits)
print(food_tuple)
So we can't change a tuple, but we can change the (mutable) things that a tuple element points to.
Anna = ['electrical']
Julie = Anna
Julie += ['physics']
print(Anna)